import { defineStore } from "pinia";
import { api, API_PREFIX } from "boot/axios";
import { LocalStorage } from "quasar";
import { useUploadWoStore } from "./uploadWoFlowStore";
import { useRouter } from "vue-router";

export const useUserStore = defineStore("user", {
  state: () => ({
    // Login Status

    loginStatus: LocalStorage.getItem("loginStatus") || false,
    access_token: LocalStorage.getItem("access_token") || null,
    refresh_token: LocalStorage.getItem("refresh_token") || null,

    // Staff Info
    currentDept: LocalStorage.getItem("currentDept") || null,
    staffID: LocalStorage.getItem("staffID") || null,
    cnName: LocalStorage.getItem("cnName") || null,

    // testing
    accounts: LocalStorage.getItem("accounts") || [], // all accounts
    domestic: LocalStorage.getItem("domestic") || [], // 4083
    export: LocalStorage.getItem("export") || [], // 1062
    others: LocalStorage.getItem("others") || [], // others
    currentPerm: LocalStorage.getItem("currentPerm")
  }),
  getters: {
    getDeptCnt: (state) => {
      return state.domestic.length + state.export.length;
    },
  },
  actions: {
    init() {
      this.loginStatus = false;
      this.access_token = null;
      this.refresh_token = null;
      this.currentDept = null;
      this.staffID = null;
      this.cnName = null;
      this.accounts = [];
      this.domestic = [];
      this.export = [];
      this.others = [];
      this.currentPerm = {}
      // clear local storage
      localStorage.clear();
    },

    async login(username, password) {
      try {
        const res = await api.post(
          API_PREFIX + "/login/",
          { username: username, password: password },
          { headers: {} }
        );
        console.log(res);
        const data = res.data;
        const status = res.status;
        console.log("data: ", data);
        console.log("status: ", status);
        this.domestic = []
        this.accounts = []
        this.export = []
        this.others = []
        if (status === 200) {
          // set Token
          this.loginStatus = true;
          this.access_token = data.token.access;
          this.refresh_token = data.token.refresh;
          // console.log("token: ", this.access_token);
          // console.log("refresh_token: ", this.refresh_token);

          // set staffCode & cnName
          // this.staffID = data.accounts.staffcode;
          this.staffID = data.accounts.staffcode;
          this.cnName = data.accounts.cnName;

          // domestic acc
          const dom = data.accounts.domestic;
          if (dom.length > 0) {
            for (let i = 0; i < dom.length; i++) {
              let d = {
                source: dom[i].Source,
                department: dom[i].department,
                deptCode: dom[i].deptCode,
                deptName: dom[i].deptName,
                accID: dom[i].id,
                userCode: dom[i].userCode,
                role: dom[i].role,
                role_chinese_name: dom[i].role_chinese_name,
                roleGroup:
                  dom[i].role.toLowerCase() === "centersender"
                    ? "DISPATCHER"
                    : dom[i].role.toLowerCase() === "worker"
                    ? "WORKER"
                    : dom[i].role.toLowerCase() === "qc" ||
                      dom[i].role.toLowerCase() === "stoneqc" ||
                      dom[i].role.toLowerCase() === "teamleader"
                    ? "QC"
                    : "unknown",
                perm: dom[i].perm
              };

              this.domestic.push(d);
              this.accounts.push(d);
            }
          }
          console.log("domestic: ", this.domestic);
          // export acc
          const exp = data.accounts.export;
          if (exp.length > 0) {
            for (let i = 0; i < exp.length; i++) {
              let e = {
                source: exp[i].Source,
                department: exp[i].department,
                deptCode: exp[i].deptCode,
                deptName: exp[i].deptName,
                accID: exp[i].id,
                userCode: exp[i].userCode,
                role: exp[i].role,
                role_chinese_name: exp[i].role_chinese_name,
                roleGroup:
                  exp[i].role.toLowerCase() === "centersender"
                    ? "DISPATCHER"
                    : exp[i].role.toLowerCase() === "worker"
                    ? "WORKER"
                    : exp[i].role.toLowerCase() === "qc" ||
                      exp[i].role.toLowerCase() === "stoneqc" ||
                      exp[i].role.toLowerCase() === "teamleader"
                    ? "QC"
                    : "unknown",
                perm: exp[i].perm
              };

              this.export.push(e);
              this.accounts.push(e);
            }
          }
          console.log("export: ", this.export);

          // others acc
          const other = data.accounts.others;
          if (other.length > 0) {
            for (let i = 0; i < other.length; i++) {
              let o = {
                source: other[i].Source,
                department: other[i].department,
                deptCode: other[i].deptCode,
                deptName: other[i].deptName,
                userCode: other[i].userCode,
                accID: other[i].id,
                role: other[i].role,
                role_chinese_name: other[i].role_chinese_name,
                roleGroup:
                  other[i].role.toLowerCase() === "centersender"
                    ? "DISPATCHER"
                    : other[i].role.toLowerCase() === "worker"
                    ? "WORKER"
                    : other[i].role.toLowerCase() === "qc" ||
                      other[i].role.toLowerCase() === "stoneqc" ||
                      other[i].role.toLowerCase() === "teamleader"
                    ? "QC"
                    : "unknown",
              };

              this.others.push(o);
              this.accounts.push(o);
            }
          }
          console.log("others: ", this.others);
          console.log("all accounts: ", this.accounts);

          // STORE TO LOCAL STORAGE
          LocalStorage.set("loginStatus", this.loginStatus);
          LocalStorage.set("access_token", this.access_token);
          LocalStorage.set("refresh_token", this.refresh_token);
          LocalStorage.set("staffID", this.staffID);
          LocalStorage.set("cnName", this.cnName);
          LocalStorage.set("accounts", this.accounts);
          LocalStorage.set("domestic", this.domestic);
          LocalStorage.set("export", this.export);
          LocalStorage.set("others", this.others);

          console.log("this.export" + this.export);
          console.log("this.others" + this.others);

          return true;
        } else {
          return false;
        }
      } catch (error) {
        console.log(error);
        return false;
      }
    },

    async pingLogin() {
      // ping 通server, 返回server的date time
      const res = await api.get(
          API_PREFIX + "/login/",
          { headers: {} }
        ); 
        return res
    },

    refreshToken(access_token) {
      LocalStorage.set("access_token", access_token);
      this.access_token = LocalStorage.getItem("access_token");
      
      console.log("new access_token", this.access_token);
    },

    setCurrentDept(accID) {
      this.currentDept = this.accounts.find((ac) => ac.accID === accID);
      console.log(this.currentDept);
      this.currentPerm = this.currentDept.perm
      LocalStorage.set("currentDept", this.currentDept);
      LocalStorage.set("currentPerm", this.currentPerm);
      const useUploadWo = useUploadWoStore();
      useUploadWo.init();

    },
    

    async logout() {
      const useUploadWo = useUploadWoStore();
      const refreshToken = this.refresh_token;
      const $router = useRouter();
      console.log('logout');
      try {
        console.log("logout" + refreshToken);
        const res = await api.post(API_PREFIX + "/logout/", {
          refresh_token: refreshToken,
        });
        useUploadWo.init();
        this.init();
        const data = res.data;
        const status = res.status;
        console.log("data: ", data);
        console.log("status: ", status);
        // call api
      } catch (error) {
        return false;
      }
    },
  },
});
